package com.woniuxy.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.text.ParseException;
import java.util.Map;

/**
 * @BelongsProject: pigTrotterStore
 * @BelongsPackage: com.woniuxy.util
 * @Author: Quan
 * @Date: 2025/3/10 18:38
 */
public class JWTUtil {
	private static final String SECRET_KEY = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9";
	/**
	 * @Description: 创建jwt
	 * @Param: userMap - [String]
	 * @Author: Quan
	 * @Date: 2025/3/10
	*/
	public static String createJWT(Map<String, Object> userMap) throws JOSEException {
		// 1、创建头部
		JWSHeader header = new JWSHeader.Builder(JWSAlgorithm.HS256)
				.type(JOSEObjectType.JWT).build();
		// 2、创建载荷
		Payload payload = new Payload(userMap);
		// 3、签名
		JWSObject jwsObject = new JWSObject(header, payload);
		JWSSigner macSigner = new MACSigner(SECRET_KEY);
		jwsObject.sign(macSigner);  // 加密方式

		return jwsObject.serialize();  // 生成jwt
	}

	/**
	 * @Description: 对jwt进行认证
	 * @Param: token - [String]
	 * @Author: Quan
	 * @Date: 2025/3/11
	*/
	public static boolean verifyJWT(String token) throws ParseException, JOSEException {
		JWSObject jwsObject = JWSObject.parse(token);
		JWSVerifier jwsVerifier = new MACVerifier(SECRET_KEY);
		return jwsObject.verify(jwsVerifier);
	}

	/**
	 * @Description: 通过反序列化得到JWSObject,获取payload
	 * @Param: token - [String]
	 * @Author: Quan
	 * @Date: 2025/3/11
	*/
	public static Integer getUserId(String token) throws ParseException {
		JWSObject jwsObject = JWSObject.parse(token);
		Map<String, Object> stringObjectMap = jwsObject.getPayload().toJSONObject();
		Long id = (Long) stringObjectMap.get("id");
		return id.intValue();
	}
}
